<template>
  <div id="hmap" ref="HMap"></div>
</template>

<script>
import Echarts from 'echarts'
import axios from 'axios'

export default {
  props: {
    type: Number,
    mapData: Array
  },
  data: () => ({
    chartInstance: null,//图标实例
    allData: null,//图表数据
    size: null//大小
  }),
  watch: {
    mapData: {
      handler: 'updateChart',
      deep: true
    }
  },
  methods: {
    async init() {
      this.chartInstance = Echarts.init(this.$refs.HMap)
      const url = '/static/map/hunan.json'
      const { data: ret } = await axios.get(url)
      Echarts.registerMap('hunan', ret)
      const initOption = {
        title: {
          text: '湖南历史名人分布',
          left: 20,
          top: 20
        },
        tooltip: {
          trigger: 'item',
          formatter: function(res) {
            return res.data.name + ':' + res.data.value + '人'
          }
        },
        geo: {
          type: 'map',
          map: 'hunan',
          top: '5%',
          bottom: '5%'
        },
        legend: {
          left: '5%',
          bottom: '5%',
          orient: 'vertical'
        },
        visualMap: {
          realtime: false,
          calculable: true,
          inRange: {
            color: ['lightskyblue', 'yellow', 'orangered']
          }
        }
      }
      this.chartInstance.setOption(initOption)
    },
    async updateChart(data) {
      //重新组合数据
      data = data.map(v => ({
        name: v.city,
        value: v.numbers
      }))

      const valueArr = []
      data.forEach(item=>{
        valueArr.push(item.value)
      })
      //获取最值
      const max = Math.max.apply(null,valueArr)
      const min = Math.min.apply(null,valueArr)

      //填入数据
      const updateOption = {
        series: [{
          data: data,
          geoIndex: 0,
          type: 'map'
        }],
        visualMap: {
          min: min,
          max: max
        }
      }
      this.chartInstance.setOption(updateOption)
    },
    screenAdapter() {
      this.size = (this.$refs.HMap.offsetWidth / 100) * 3.6
      const adaptOption = {
        title: {
          textStyle: {
            fontSize: this.size / 2
          }
        },
        legend: {
          itemWidth: this.size / 2,
          itemHeight: this.size / 2,
          itemGap: this.size / 2,
          textStyle: {
            fontSize: this.size / 2
          }
        },
        geo: {
          label: {
            fontSize: this.size / 3.5
          }
        },
        tooltip: {
          textStyle: {
            fontSize: this.size / 3.5
          }
        }
      }
      this.chartInstance.setOption(adaptOption)
      this.chartInstance.resize()
    }
  },
  mounted() {
    this.init()
    window.addEventListener('resize', this.screenAdapter)
    this.screenAdapter()
  },
  destroyed() {
    window.removeEventListener('resize', this.screenAdapter)
  }
}
</script>

<style scoped>
#hmap {
  height: 100%;
  width: 100%;
}
</style>
